package com.ebuy.api.base.exception;



import com.ebuy.api.base.dto.BaseResp;
import com.ebuy.api.base.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@Slf4j
@ControllerAdvice
public class ExceptionHandlerAdvice {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleArgumentNotValidException(MethodArgumentNotValidException exp) {
        exp.printStackTrace();
        log.error(exp.getMessage());
        FieldError error = exp.getBindingResult().getFieldErrors().get(0);
        BaseResp result = new BaseResp(
                BaseResp.FAIL, error.getDefaultMessage(), error.getField());
        return new ResponseEntity<>(JsonUtil.toJson(result), HttpStatus.OK);
    }

    @ExceptionHandler(BizException.class)
    public ResponseEntity<String> handleBizException(BizException exp) {
        exp.printStackTrace();
        log.error(exp.getMessage());
        BaseResp result = new BaseResp(BaseResp.FAIL, exp.getMessage());
        return new ResponseEntity<>(JsonUtil.toJson(result), HttpStatus.OK);
    }


    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException exp) {
        exp.printStackTrace();
        log.error(exp.getMessage());
        BaseResp result = new BaseResp(BaseResp.FAIL, exp.getMessage());
        return new ResponseEntity<>(JsonUtil.toJson(result), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
